# encoding:utf-8
from flask import Flask
from flask_cors import CORS
from flask_restful import Api
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor
import flask_whooshalchemyplus
from flask_whooshalchemyplus import index_all


from common.models import db, cache
from cloud_info_flask.account.user import user_bp
from cloud_info_flask.account.oauth_user import oauth2_bp
from cloud_info_flask.course.course import course_bp
from cloud_info_flask.comment.comment import comment_bp
from cloud_info_flask.pay.pay import pay_bp
from cloud_info_flask.account.super_user import vip_bp
from cloud_info_flask.study_path.stupy_path import path_bp

from common.models.course import Course, Tag
from common.models.book import Book


from cloud_info_flask.book_manage.book import book_bp
from common.utils.middlewares import jwt_authentication
from common.cron_task.news_task import update_recommend_list
# from celery_task.main import celery_app
from logs.logs import setup_log


def cron_test():
    print('这是测试定时任务')


def create_flask_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    app.before_request(jwt_authentication)
    db.init_app(app)
    # flask_whooshalchemyplus.init_app(app)
    # with app.app_context():
    #     index_all(app)
    cache.init_app(app)

    app.register_blueprint(user_bp)
    app.register_blueprint(book_bp)
    app.register_blueprint(course_bp)
    app.register_blueprint(oauth2_bp)
    app.register_blueprint(comment_bp)
    app.register_blueprint(pay_bp)
    app.register_blueprint(vip_bp)
    app.register_blueprint(path_bp)

    setup_log('testing')
    cors = CORS(app, resources={r"/*/*": {"origins": "*"}})

    # 配置定时任务
    executors = {
        'default': ThreadPoolExecutor(10)
    }
    app.scheduler = BackgroundScheduler(executors=executors)
    # 每隔一分钟执行一次
    # app.scheduler.add_job(update_recommend_list, trigger='interval', hours=1, args=[cache, app])
    # app.scheduler.add_job(update_recommend_list, trigger='date', args=[cache, app])
    # app.scheduler.add_job(func=cron_test, trigger='interval', seconds=10)
    # app.scheduler.add_job(func=GetUserAttentionNew, trigger='date')
    # app.scheduler.start()
    # app.celery_ins = celery_app
    api = Api(app)
    return app
